package org.jcms.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcms.model.Book;
import org.jcms.service.BookServiceI;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ManagerAddBookInfomation extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public ManagerAddBookInfomation() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * private String bookIsbn; private String bookName; private String
	 * bookPublisher;
	 * 
	 * private String bookAuthor; private Integer bookStock;// private Integer
	 * bookOrderNumber;// private Double bookPrice;
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ApplicationContext ac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		BookServiceI bookServiceI = (BookServiceI) ac
				.getBean("bookServiceImpl");
		String retJson = "{\"error\":@err,\"msg\":\"@msg\"}";
		String err = "1";
		String msg = "";
		String bookIsbn = request.getParameter("ISBN");
		String bookName = request.getParameter("bookName");
		String bookPublisher = request.getParameter("bookPublisher");
		String bookAuthor = request.getParameter("bookAuthor");
		String bookPrice = request.getParameter("bookPrice");
		Double doubleBookPrice = 0.0;
		try {
			
			if(bookIsbn==null||"".equals(bookIsbn)){
				msg="教材ISBN不能为空";
			}else{
				if(bookPrice==null||!bookPrice.matches("\\+?\\d+(\\.\\d+)?")){
					msg="教材价格填写不正确";
				}else{
					doubleBookPrice = Double.valueOf(bookPrice);
					 Book book = bookServiceI.findById(bookIsbn);
					 if(book!=null){
						 msg = "教材已存在";
					 }else{
						 Book newBook = new Book(bookIsbn, bookName, bookPublisher, null, bookAuthor, 0, 0, doubleBookPrice);
						 bookServiceI.create(newBook);
						 msg = "教材入("+bookIsbn+")库成功";
						 err="0";
					 }
				}
				
				
			}
		} catch (Exception e) {
          msg = "系统出错";
		} finally {
			retJson = retJson.replace("@err", err);
			retJson = retJson.replace("@msg", msg);
			response.getOutputStream().write(retJson.getBytes("utf-8"));
		}
	}

	public void init() throws ServletException {

	}

}
